package com.jyu.apts.utils;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

import com.aliyun.oss.OSSClient;

public class AliyunOSSUtil {
	private static final String END_POINT = "";
	private static final String ACCESS_KEY_ID = "";
	private static final String ACCESS_KEY_Secret = "";
	private static final String BUCKET_NAME = "";
	private static final Integer EXPIRE_HOURS = 6;//单次生成的url过期时间，单位小时
	private static final Integer CLEAR_SAFE_MINS = 6;//提前几分钟清理过期缓存
	public static String upload(InputStream inputStream,String suffix){
		String objectName = UUID.randomUUID().toString().replace("-", "")+"."+suffix;
		OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_Secret);
		// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
		ossClient.putObject(BUCKET_NAME, objectName, inputStream);
		// 关闭OSSClient。
		ossClient.shutdown();
		return objectName;
	}
	
	public static URLCache generateUrlCache(String objectName) {
		OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_Secret);
		// 设置URL过期时间为6小时。
		Date expiration = new Date(new Date().getTime() + 3600 * 1000 * EXPIRE_HOURS);
		// 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
		URL url = ossClient.generatePresignedUrl(BUCKET_NAME, objectName, expiration);
		// 关闭OSSClient。
		ossClient.shutdown();
		URLCache urlCache = new URLCache();
		urlCache.url = url;
		urlCache.expiration = DateUtil.addMins(expiration, -CLEAR_SAFE_MINS);
		return urlCache;
	}
	
	public static void delete(String objectName) {
		try {
		OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_Secret);
		ossClient.deleteObject(BUCKET_NAME, objectName);
		ossClient.shutdown();
		}catch(Exception e) {
			System.out.println(objectName+"already delete");
		};
	}

	public static long getSize(String objectName) {
		OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_Secret);
		long size = ossClient.getSimplifiedObjectMeta(BUCKET_NAME, objectName).getSize();
		ossClient.shutdown();
		return size;
	}
	
}
